//
//  MainViewController.m
//  AIM
//
//  Created by user10 on 2017/5/15.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "MainViewController.h"
#import "ViewController.h"
#import "AppDelegate.h"
#import "Goods.h"
#import "MainTableViewCell.h"
#import "MainDetaileViewController.h"
#import "EnteringViewController.h"
#import "AreaTableViewController.h"
#import "NetWorkTools.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "MyLog.h"
#import "logModel.h"
#import "DataBase.h"

@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,mainDetaileDelegate,EnteringViewDelegate>
{
    NSMutableArray *tableData;
}
@property (assign,nonatomic)BOOL transiting;
@property (weak, nonatomic) IBOutlet UITableView *GoodsTableView;
@property (weak, nonatomic) IBOutlet UIButton *LogOutBtn;
@property (strong,nonatomic)NSMutableArray *modelArr;
@property (strong,nonatomic)NSString *minTime;
@property (strong,nonatomic)NSString *maxTime;


@end

@implementation MainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //设置按钮圆角
    _LogOutBtn.layer.cornerRadius = 5;
    //初始化表格数据
    tableData = [[NSMutableArray alloc] init];
    for  (int  i = 0; i< 50; i++) {
        [tableData addObject:[NSString stringWithFormat:@"MyCellDemon%i" ,i]];
    }
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self loadNew];
    self.GoodsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新的网络请求的处理
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadNew];
            [self.GoodsTableView reloadData];
            [self.GoodsTableView.mj_header endRefreshing];
        });
    }];
    
    self.GoodsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"%@",_minTime);
        // 上拉加载的网络请求的处理
        NSLog(@"%@--%@",self.maxTime,self.minTime);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadOld];
            [self.GoodsTableView.mj_footer endRefreshing];
        });
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:self];
}
- (IBAction)refrensh:(id)sender {
    [_GoodsTableView setContentOffset:CGPointMake(0,0) animated:YES];
}


- (void)loadOld{
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSLog(@"有网");
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:getWhatsneweData>\
                                       <arg0>%@</arg0>\
                                       <arg1>50</arg1>\
                                       <arg2>%@</arg2>\
                                       <arg3>%@</arg3>\
                                       <arg4>0</arg4>\
                                       </web:getWhatsneweData>",COMPANY,self.maxTime,self.minTime];
            //初始化网络请求类
            NetWorkTools *tools = [NetWorkTools shareTools];
            
            //发送网络请求
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/WhatsnewImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                //请求回来的字符串结果
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                //截取返回失败的结果字符串
                NSRange returnRange = [string rangeOfString:@"<return>"];
                NSRange returnendRange = [string rangeOfString:@"</return>"];
                NSRange rangeEnd = NSMakeRange(returnRange.location + returnRange.length, returnendRange.location - returnRange.location - returnRange.length);
                if (rangeEnd.location != NSNotFound) {
                    NSString *successResultStr = [string substringWithRange:rangeEnd];
                    //判断是否有需要的结束数据
                    if (![successResultStr isEqualToString:@"FAILED"]) {
                        //截取返回成功的结果字符串
                        NSRange startRange = [string rangeOfString:@"@@"];
                        NSRange endRange = [string rangeOfString:@"</return>"];
                        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                        NSString *resultString = [string substringWithRange:range];
                        NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                        
                        NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                        self.minTime = [getDict objectForKey:@"MIN_DATE"];
                        NSMutableArray *arr = [NSMutableArray arrayWithArray:[getDict objectForKey:@"TABLE_KEY"]];
                        [_modelArr addObjectsFromArray:arr];
                        [_GoodsTableView reloadData];
                        NSString *newDataStr = [getDict objectForKey:@"NEW_DATA"];
                        //判断是否有新的数据存在
                        if ([newDataStr isEqualToString:@"1"]) {
                            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Reminder" message:@"Discover new data" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
                            [alert show];
                        }
                    }
                }else{
                    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"NetWork error" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }];

        }else{
            NSLog(@"没有网");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
}



//下拉刷新的网络请求
- (void)loadNew
{
    _modelArr = nil;
    //网络判断
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            
            NSLog(@"有网");
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:getWhatsneweData>\
                                       <arg0>%@</arg0>\
                                       <arg1>50</arg1>\
                                       <arg2></arg2>\
                                       <arg3></arg3>\
                                       <arg4>0</arg4>\
                                       </web:getWhatsneweData>",COMPANY];
            //初始化网络工具类
            NetWorkTools *tools = [NetWorkTools shareTools];
            //发送网络请求
            
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/WhatsnewImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                //截取返回失败的结果字符串
                NSRange returnRange = [string rangeOfString:@"<return>"];
                NSRange returnendRange = [string rangeOfString:@"</return>"];
                NSRange rangeEnd = NSMakeRange(returnRange.location + returnRange.length, returnendRange.location - returnRange.location - returnRange.length);
                if (rangeEnd.location != NSNotFound) {
                    NSString *successResultStr = [string substringWithRange:rangeEnd];
                    //判断是否返回了错误的字符串
                    if (![successResultStr isEqualToString:@"FAILED"]) {
                        NSRange startRange = [string rangeOfString:@"@@"];
                        NSRange endRange = [string rangeOfString:@"</return>"];
                        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                        NSString *resultString = [string substringWithRange:range];
                        NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                        
                        self.minTime = [getDict objectForKey:@"MIN_DATE"];
                        self.maxTime = [getDict objectForKey:@"MAX_DATE"];
                        NSMutableArray *arr = [NSMutableArray arrayWithArray:[getDict objectForKey:@"TABLE_KEY"]];
                        _modelArr = arr;
                        //刷新tableView
                        [_GoodsTableView reloadData];
                        NSString *newDataStr = [getDict objectForKey:@"NEW_DATA"];
                        if ([newDataStr isEqualToString:@"1"]) {
                            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Reminder" message:@"Discover new data" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
                            [alert show];
                        }
                    }
                }else{
                    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"NetWork error" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }];

        }else
        {
            //网络错误提醒
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];
}



- (IBAction)write:(UIButton *)sender {
    NSLog(@"编辑");
    EnteringViewController *enteringViewController = [[EnteringViewController alloc]init];
    enteringViewController.EnteringDelegate = self;
    [self.navigationController pushViewController:enteringViewController animated:YES];
    
}
//中间按钮点击事件
- (IBAction)listBtn:(UIButton *)sender {
    NSLog(@"中间按钮");
}
//左边按钮点击事件
- (IBAction)functionBtn:(UIButton *)sender {
    NSLog(@"Mune按钮");
}


- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    //tableViewCell点击进入下一页  返回之后取消选中状态
    [self.GoodsTableView deselectRowAtIndexPath:[self.GoodsTableView indexPathForSelectedRow] animated:YES];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillDisappear:animated];
}
//搜索按钮的点击事件
- (IBAction)searchBtn:(UIButton *)sender {
    
    NSLog(@"搜索");
}
//退出按钮的点击事件
- (IBAction)logOutBtn:(UIButton *)sender {
    
    NSLog(@"退出");
    
    //Alert弹层
    NSString *title = NSLocalizedString(@"Log out", nil);
    NSString *message = NSLocalizedString(@"Are you sure you want to quit？", nil);
    NSString *cancelButtonTitle = NSLocalizedString(@"Cancel", nil);
    NSString *otherButtonTitle = NSLocalizedString(@"OK", nil);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [[MyLog shareMyLog]addWithOperation:@"退出成功" type:nil name:nil];
        NSDate *date = [NSDate date]; // 获得时间对象
        
        NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
        
        [forMatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
        
        NSString *dateStr = [forMatter stringFromDate:date];
        
        logModel *log = [[logModel alloc]init];
        log.time = dateStr;
        log.opration = @"LOGINOUT success";
        log.type = @"";
        log.filename = @"";
        
        [[DataBase sharedDataBase]addLogModel:log];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController * vc = [story instantiateViewControllerWithIdentifier:@"TranslateController"];
        [self presentViewController:vc animated:YES completion:nil];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user removeObjectForKey:@"login"];
        [user removeObjectForKey:@"TANTO_CD"];
    }];
    // Add the 事件.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - MainDetaileViewController delegate func
- (void)refreash{
    //开始下拉刷新
    [self.GoodsTableView.mj_header beginRefreshing];
}

#pragma mark - EnteringViewController delegate func
- (void)refreshOnce{
    //开始下拉刷新
    [self.GoodsTableView.mj_header beginRefreshing];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_modelArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //指定cellIdentifier为自定义的cell
    static  NSString *CellIdentifier = @"TableViewCell" ;
    //自定义cell类
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MainTableViewCell"  owner:self options:nil] lastObject];
    }
    //添加测试数据
    cell.time.text = [_modelArr[indexPath.row] objectForKey:@"ROW_CREATE_DATE"];
    cell.CategoryContentL.text = [_modelArr[indexPath.row] objectForKey:@"ROW_CATEGORY_NAME"];
    cell.FromContentL.text = [_modelArr[indexPath.row] objectForKey:@"ROW_SHOP_NAME"];
    cell.TitleContentL.text = [_modelArr[indexPath.row] objectForKey:@"ROW_TITLE"];
    cell.userNameL.text = [_modelArr[indexPath.row] objectForKey:@"ROW_TANTO_NAME"];
    cell.messageId = [_modelArr[indexPath.row] objectForKey:@"ROW_MESSAGE_ID"];
    NSString *type = [_modelArr[indexPath.row] objectForKey:@"ROW_DATA_TYPE"];
    //设置图片
    if ([type isEqualToString:@"AUDIO"]) {
        cell.image.hidden = NO;
        cell.textTitle.hidden = YES;
        cell.textContent.hidden = YES;
        cell.image.contentMode = UIViewContentModeCenter;
        [cell.image setImage:[UIImage imageNamed:@"play_r6"]];
    }else if ([type isEqualToString:@"TEXT"]){
        cell.image.hidden = NO;
        cell.textTitle.hidden = YES;
        cell.textContent.hidden = YES;
        cell.image.contentMode = UIViewContentModeScaleAspectFit;
//        cell.textTitle.text = [_modelArr[indexPath.row] objectForKey:@"ROW_TITLE"];
//        cell.textTitle.textColor = [UIColor redColor];
//        cell.textContent.text = [_modelArr[indexPath.row] objectForKey:@"ROW_MEMO"];
        [cell.image setImage:[UIImage imageNamed:@"icon"]];
    }else{
        cell.image.hidden = NO;
        cell.textTitle.hidden = YES;
        cell.textContent.hidden = YES;
        cell.image.contentMode = UIViewContentModeScaleAspectFit;
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[_modelArr[indexPath.row] objectForKey:@"ROW_IMAGE"]] placeholderImage:[UIImage imageNamed:@"icon"]];
    }
    
    return cell;
    
}

#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //得到storyBoard
    UIStoryboard *tabBarSB = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    //得到VC
    MainDetaileViewController *VC = [tabBarSB instantiateViewControllerWithIdentifier:@"Main"];
    VC.messageId = cell.messageId;
    VC.delegate = self;
    [self.navigationController pushViewController:VC animated:YES];

}
- (IBAction)RefrenshBtn:(id)sender {
}
@end
